package cn.bby.query.server.infrastructure.db.repository;

import cn.bby.query.server.domain.agg.sys.repository.HealthInfoRepository;
import cn.bby.query.server.domain.share.constant.HealthInfoMetric;
import cn.bby.query.server.infrastructure.db.entity.HealthInfo;
import cn.bby.query.server.infrastructure.db.mapper.HealthInfoMapper;
import cn.hutool.core.collection.CollStreamUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.ChainWrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author wangbenyin
 * @version 1.0
 * @date 2025/06/10
 * @since 17
 */
@Component
@RequiredArgsConstructor
public class HealthInfoRepositoryImpl implements HealthInfoRepository {
    private final HealthInfoMapper healthInfoMapper;

    @Override
    public void initAndCreateBatch(List<HealthInfoMetric> metrics) {
        if (metrics.isEmpty()) {
            return;
        }
        boolean exists = healthInfoMapper.exists(
                Wrappers.lambdaQuery(HealthInfo.class)
                        .in(HealthInfo::getMetric, CollStreamUtil.toList(metrics, metric -> metric.metric))
        );
        if (exists) {
            return;
        }
        healthInfoMapper.insert(metrics.stream()
                .map(metric -> new HealthInfo()
                        .setMetric(metric.metric)
                        .setValue(metric.defaultValue))
                .toList()
        );
    }

    @Override
    public void update(HealthInfoMetric metric, Long value) {
        ChainWrappers.lambdaUpdateChain(healthInfoMapper)
                .eq(HealthInfo::getMetric, metric.metric)
                .set(HealthInfo::getValue, value)
                .update();
    }

    @Override
    public boolean isHealth(List<String> metrics) {
        return healthInfoMapper.exists(Wrappers.lambdaQuery(HealthInfo.class)
                .in(HealthInfo::getMetric, metrics)
                .apply(" (now() - update_time) > '00:00:30'::interval")
        );
    }

    @Override
    public void writeLog(Long interfaceId, String msg) {

    }
}
